/*
 * @Author: xiangmin 
 * @File: 常用工具
 * @Date: 2018-09-05 17:20:04 
 * @Last Modified by: xiangmin
 * @Last Modified time: 2018-08-13 18:03:59
 */
let util = {};

util.title = function (title) {
    title = title ? title : '管理系统';
    window.document.title = title;
};


/**
* 数组转递归
* @param  {Array} data   [数据源]
* @param  {Object} option [配置项]
* id 默认为id
* label 默认设置中的key
* labelName tree中的key(label所对应的值)
* parent   父id key
* @return {Array}        [递归数组]
*/
util.getTree = function(data, option) {
    let targetId = option.id ? option.id : 'id';
    let label = option.label || "name";
    let labelName = option.labelName || 'label';
    let parent = option.parent || "_parentId";

    function a(data, id, child) {
        let result = [],
            temp;
        child = child ? child : 'children';
        let _len = data.length;
        for (let i = 0; i < _len; i++) {
            let item = data[i];
            if (item[parent] == id) {
                let obj = {};
                for (let key in item) {
                    obj[key] = item[key]
                }
                obj[labelName] = item[label];
                obj.id = item[targetId];
                temp = a(data, item[targetId], child);
                if (temp.length > 0) {
                    obj[child] = temp;
                }
                result.push(obj);
            }
        }
        return result;
    }
    return a(data)
}


// 深拷贝
export function deepCopy(o, t) {
    if (typeof o != 'object') {
        new Error('参数错误！')
    } else {
        var t = t || {};
        for (var i in o) {
            if (typeof o[i] == 'object' && o[i] != null) {
                t[i] = Object.prototype.toString.call(o[i]) == '[object Array]' ? [] : {};
                deepCopy(o[i], t[i]);
            } else {
                t[i] = o[i];
            }
        }
        return t;
    }

}

export default util;